#!/usr/bin/python3.7
# -*- coding: utf-8 -*-

import pymysql
import conf
import Pool


# pool = PooledDB(pymysql, 5, host=conf.db_host, user=conf.db_user_name, passwd=conf.db_user_pwd, db=conf.db_name, port=3306, charset=conf.db_charset)
def create_conn():
    print(('host {}, db {}'.format(conf.db_host, conf.db_name)))
    cx = pymysql.connect(conf.db_host, conf.db_user_name, conf.db_user_pwd, conf.db_name, charset=conf.db_charset, port=conf.db_port)
    return cx


def release_conn():
    pool.clear()
    return None


pool = Pool.Pool(create_conn, 0)


# execute sql
def execute_sql(sql, args=None):
    global pool
    cx = pool.get()
    cu = cx.cursor()
    try:
        ret = cu.execute(sql, args)
        cx.commit()
    except Exception as e:
        print(sql)
        raise e
    finally:
        cu.close()
        pool.put(cx)
    return ret  # >= 0


# execute sql
def execute_fetchall(sql, args=None):
    global pool
    cx = pool.get()
    cu = cx.cursor()
    record_set = []
    if cu.execute(sql, args):
        record_set = cu.fetchall()
    cu.close()
    pool.put(cx)
    return record_set


# execute sql
def execute_fetchone(sql, args=None):
    global pool
    cx = pool.get()
    cu = cx.cursor()
    record_set = []
    if cu.execute(sql, args):
        record_set = cu.fetchone()
    cu.close()
    pool.put(cx)
    return record_set


# add user
def default_insert_user(name, pwd, host='n12.mysticalcard.com'):
    sql = "insert into user (name, pwd, host)values('{}', '{}', '{}')".format(name, pwd, host)
    return execute_sql(sql)

